#!/usr/bin/env python3
import os
import re
import yaml
from pathlib import Path

def migrate_yaml_file(file_path):
    """迁移YAML文件中的旧格式到新格式"""
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        original_content = content
        
        # 处理字段级别的旧格式
        # 匹配字段定义并转换为rules格式
        def replace_field_validation(match):
            field_content = match.group(0)
            lines = field_content.split('\n')
            
            # 提取现有的rules
            rules = []
            new_lines = []
            skip_next = False
            
            for i, line in enumerate(lines):
                if skip_next:
                    skip_next = False
                    continue
                    
                if 'required: true' in line:
                    rules.append('required')
                elif 'unique: true' in line:
                    rules.append('unique')
                elif 'format: email' in line:
                    rules.append('format: email')
                elif re.search(r'validation:\s*\{', line):
                    # 跳过嵌套validation格式
                    skip_next = True
                    continue
                else:
                    new_lines.append(line)
            
            # 如果有rules需要添加
            if rules:
                # 找到type行的位置
                type_line_idx = -1
                for i, line in enumerate(new_lines):
                    if 'type:' in line:
                        type_line_idx = i
                        break
                
                if type_line_idx >= 0:
                    # 在type行后添加rules
                    indent = len(new_lines[type_line_idx]) - len(new_lines[type_line_idx].lstrip())
                    rules_lines = [' ' * indent + 'rules:']
                    for rule in rules:
                        rules_lines.append(' ' * (indent + 2) + f'- {rule}')
                    
                    new_lines = new_lines[:type_line_idx+1] + rules_lines + new_lines[type_line_idx+1:]
            
            return '\n'.join(new_lines)
        
        # 使用正则表达式匹配字段定义
        field_pattern = r'(\s+\w+:\s*\n(?:\s+[^:\n]+:[^\n]*\n)*)'
        content = re.sub(field_pattern, replace_field_validation, content, flags=re.MULTILINE)
        
        # 如果内容有变化，写回文件
        if content != original_content:
            with open(file_path, 'w', encoding='utf-8') as f:
                f.write(content)
            print(f"✅ 迁移完成: {file_path}")
            return True
        else:
            print(f"⏭️  无需迁移: {file_path}")
            return False
            
    except Exception as e:
        print(f"❌ 迁移失败: {file_path} - {e}")
        return False

def migrate_ts_file(file_path):
    """迁移TypeScript文件中的旧格式"""
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        original_content = content
        
        # 简单的字符串替换
        replacements = [
            (r"required:\s*true", "rules: ['required']"),
            (r"unique:\s*true", "rules: ['unique']"),
            (r"format:\s*email", "rules: ['format: email']"),
        ]
        
        for pattern, replacement in replacements:
            content = re.sub(pattern, replacement, content)
        
        if content != original_content:
            with open(file_path, 'w', encoding='utf-8') as f:
                f.write(content)
            print(f"✅ 迁移完成: {file_path}")
            return True
        else:
            print(f"⏭️  无需迁移: {file_path}")
            return False
            
    except Exception as e:
        print(f"❌ 迁移失败: {file_path} - {e}")
        return False

def main():
    """主函数"""
    print("🚀 开始迁移旧格式到标准rules格式...")
    
    test_dir = Path("tests")
    migrated_count = 0
    
    # 遍历所有测试文件
    for file_path in test_dir.rglob("*"):
        if file_path.is_file():
            if file_path.suffix in ['.yml', '.yaml']:
                if migrate_yaml_file(file_path):
                    migrated_count += 1
            elif file_path.suffix == '.ts':
                if migrate_ts_file(file_path):
                    migrated_count += 1
    
    print(f"\n🎉 迁移完成！共迁移了 {migrated_count} 个文件")

if __name__ == "__main__":
    main()